package com.education.welco.controller;


import com.education.common.pojo.AjaxResult;
import com.education.common.pojo.SysAppUser;
import com.education.common.pojo.TStudent;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.welco.feign.userFeign;
import com.education.welco.pojo.TClass;
import com.education.welco.pojo.TSchooldept;
import com.education.welco.service.ITClassService;
import com.education.welco.service.ITSchooldeptService;
import com.education.welco.service.ITStudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 学生入学 信息操作处理
 *
 * @author d
 * @date 2020-05-08
 */
@RestController("tStudentController")
@RequestMapping("/tStudent")
public class TStudentController {

    @Autowired
    private ITStudentService studentService;
    @Autowired
    private userFeign userFeign;
    @Autowired
    private ITSchooldeptService schooldeptService;
    @Autowired
    private ITClassService classService;

    public TStudentController(ITStudentService studentService,
                              userFeign userFeign,
                              ITSchooldeptService schooldeptService,
                              ITClassService classService) {
        this.studentService = studentService;
        this.userFeign = userFeign;
        this.schooldeptService = schooldeptService;
        this.classService = classService;
    }

    /**
     * 教务端
     * 查询学生列表
     */
    @GetMapping("/list")
    public ApiReturnObject list(TStudent student, Integer pageNum, Integer pageSize) {
        String isBind = "";
        if (student.getIsBind() != null) {
            isBind = student.getIsBind();
        }
        //全部    根据部门 手机号 筛选 studentName  deptId
        List<TStudent> tStudents1 = new ArrayList<>();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<TStudent> tStudents = studentService.selectTStudentListOther2(student);
        for (TStudent tStudent : tStudents) {
            if (tStudent.getImgUrl() == null) {
                tStudent.setImgUrl("");
            }
            //判断学生当前是否在线
            String signTime = tStudent.getSignTime();
            //获取系统当前时间
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            try {
                if (StringUtils.isNotEmpty(signTime)) {
                    Date parse = simpleDateFormat.parse(signTime);
                    Date parse1 = simpleDateFormat.parse(format);
                    if (parse1.getTime() - parse.getTime() < 60000) {
                        TStudent tStudent1 = new TStudent();
                        tStudent1.setState(1);
                        tStudent1.setUserId(tStudent.getUserId());
                        studentService.updateByUserId(tStudent1);
                        //return new ApiReturnObject("200","该学生在线","");
                    } else {
                        TStudent tStudent1 = new TStudent();
                        tStudent1.setState(2);
                        tStudent1.setUserId(tStudent.getUserId());
                        studentService.updateByUserId(tStudent1);
                        //return new ApiReturnObject("200","该学生不在线","");
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //判断绑定状态
            if (tStudent.getUserId() != null) {
                tStudent.setIsBind("1");
            } else {
                tStudent.setIsBind("0");
            }
        }
        //选择了状态
        if (!"".equals(isBind)) {
            List<TStudent> tStudents2 = studentService.selectTStudentListOther2(student);
            for (TStudent tStudent : tStudents2) {
                if (tStudent.getImgUrl() == null) {
                    tStudent.setImgUrl("");
                }
                //判断绑定状态
                if (tStudent.getUserId() != null) {
                    tStudent.setIsBind("1");
                } else {
                    tStudent.setIsBind("0");
                }
            }
            for (TStudent tStudent : tStudents2) {
                //状态匹配
                if (tStudent.getIsBind().equals(isBind)) {
                    tStudents1.add(tStudent);
                }
            }
            PageInfo<TStudent> pageInfo = new PageInfo<>(tStudents1);
            return new ApiReturnObject("200", "查询成功", pageInfo);
        }
        PageInfo<TStudent> pageInfo = new PageInfo<>(tStudents);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }

    /**
     * 老师端-学生申请进班通过与驳回接口
     *
     * @param student
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/pasrejbytea")
    public ApiReturnObject pasrejbytea(TStudent student) {
        int i = studentService.updateTStudent(student);
        //此处的state为1通过2驳回
        if ("1".equals(student.getApplicationStatus())) {
            TStudent tStudent = studentService.selectTStudentById(student.getId());
            //用户表对应用户添加学校id和班级id  (审核通过后在修改用户表的状态)
            studentService.updateInfoForUser(tStudent.getUserId(), tStudent.getClassId(), tStudent.getSchoolId(), 1, 2);
            return new ApiReturnObject("200", "通过成功!", "");
        }
        return new ApiReturnObject("200", "驳回成功!", "");
    }

    /**
     * 老师端班级下拉列表查询
     *
     * @param teacherId
     * @return
     */
    @GetMapping("/classListByTeaId")
    public ApiReturnObject selectClassListByTeaId(Integer teacherId) {
        List<TClass> tClasses = studentService.selectClassListByTeaId(teacherId);
        return new ApiReturnObject("200", "班级下拉列表查询成功!", tClasses);
    }

    /**
     * 查询学生列表(代课老师查询学生列表)
     */
    @GetMapping("/stulistbytea")
    public ApiReturnObject stulistbytea(TStudent student, Integer pageNum, Integer pageSize) {
        String isBind = "";
        if (student.getIsBind() != null) {
            isBind = student.getIsBind();
        }
        //全部    根据部门 手机号 筛选 studentName  deptId
        ArrayList<TStudent> tStudents1 = new ArrayList<>();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<TStudent> tStudents = studentService.selectStudentListRemovebohui(student);

        for (TStudent tStudent : tStudents) {
            if (tStudent.getImgUrl() == null) {
                tStudent.setImgUrl("");
            }
            //判断学生当前是否在线
            String signTime = tStudent.getSignTime();
            //获取系统当前时间
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            try {
                if (StringUtils.isNotEmpty(signTime)) {
                    Date parse = simpleDateFormat.parse(signTime);
                    Date parse1 = simpleDateFormat.parse(format);
                    if (parse1.getTime() - parse.getTime() < 60000) {
                        TStudent tStudent1 = new TStudent();
                        tStudent1.setState(1);
                        tStudent1.setUserId(tStudent.getUserId());
                        studentService.updateByUserId(tStudent1);
                        //return new ApiReturnObject("200","该学生在线","");
                    } else {
                        TStudent tStudent1 = new TStudent();
                        tStudent1.setState(2);
                        tStudent1.setUserId(tStudent.getUserId());
                        studentService.updateByUserId(tStudent1);
                        //return new ApiReturnObject("200","该学生不在线","");
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //判断绑定状态
            if (tStudent.getUserId() != null) {
                tStudent.setIsBind("1");
            } else {
                tStudent.setIsBind("0");
            }
        }
        //选择了状态
        if (!"".equals(isBind)) {
            List<TStudent> tStudents2 = studentService.selectTStudentListOther2(student);
            for (TStudent tStudent : tStudents2) {
                if (tStudent.getImgUrl() == null) {
                    tStudent.setImgUrl("");
                }
                //判断绑定状态
                if (tStudent.getUserId() != null) {
                    tStudent.setIsBind("1");
                } else {
                    tStudent.setIsBind("0");
                }
            }
            for (TStudent tStudent : tStudents2) {
                //状态匹配
                if (tStudent.getIsBind().equals(isBind)) {
                    tStudents1.add(tStudent);
                }
            }
            PageInfo<TStudent> pageInfo = new PageInfo<>(tStudents1);
            return new ApiReturnObject("200", "查询成功", pageInfo);
        }

        PageInfo<TStudent> pageInfo = new PageInfo<>(tStudents);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }


    /**
     * 学生查询详情
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id) {
        TStudent tStudent = studentService.selectTStudentById(id);
        ArrayList<Integer> arrayList = Lists.newArrayList();
        if (tStudent.getClassId() != null) {
            //编辑classIdList数组  根据班级id查找系
            TClass tClass = classService.selectTClassById(tStudent.getClassId());
            TSchooldept schooldept = schooldeptService.selectTSchooldeptByClassId(tClass.getDeptId());
            if (schooldept != null) {
                arrayList.add(schooldept.getId());
            }
            arrayList.add(tStudent.getClassId());
        }
        tStudent.setClassIdList(arrayList);
        return new ApiReturnObject("200", "查询成功", tStudent);
    }

    //查询学生
    @GetMapping("/selectstudent")
    public TStudent selectstudent(Integer userId) {
        TStudent tStudent = studentService.selectTStudentById2(userId);
        return tStudent;
    }

    /**
     * 导入学生信息
     */
    @RequestMapping(value = "/threeImport", method = RequestMethod.POST)
    public AjaxResult threeExImport(@RequestParam("file") MultipartFile file,
                                    @RequestParam("schoolId") Integer schoolId) {
        String fileName = file.getOriginalFilename();
        try {
            Boolean a = studentService.threeBatchQuesionImport(fileName, file, schoolId);
            if (a) {
                return AjaxResult.success("导入成功！");
            } else {
                return AjaxResult.error(201, "导入失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(201, e.getMessage());
        }
    }

    /**
     * 教务端
     * 添加学生
     */
    @PostMapping("/add")
    public ApiReturnObject add(@RequestBody TStudent student) {
        TStudent tStudent = new TStudent();
        //根据手机号判断是否存在
        if (!"".equals(student.getPhone())) {
            tStudent.setPhone(student.getPhone());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该手机号已存在", "");
            }
        }
        //根据身份证判断是否存在
        tStudent.setPhone("");
        if (!"".equals(student.getIdcardno())) {
            tStudent.setIdcardno(student.getIdcardno());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该身份证号已存在", "");
            }
        }
        //设置班级id
        if (student.getClassIdList() != null && student.getClassIdList().size() > 1) {
            student.setClassId(student.getClassIdList().get(1));
        }
        SysAppUser appUser = new SysAppUser();
        appUser.setClassId(student.getClassId());
        appUser.setSchoolId(student.getSchoolId());
        appUser.setSysPhone(student.getPhone());
        appUser.setIdcardno(student.getIdcardno());
        appUser.setCreateTime(new Date());
        appUser.setSysRelname(student.getStudentName());

        int id;
        boolean bool = userFeign.findUserBySchoolId2(student.getPhone());
        if (bool) {
            //账号存在不新增
            //查询已存在的用户id与学生表建立关联关系
            ApiReturnObject sysUserBysysPhone = userFeign.findSysUserBysysPhone(student.getPhone());
            id = (int) sysUserBysysPhone.getReturnObject();
            //用户表对应用户添加学校id和班级id以及用户类型
            studentService.updateInfoForUser(id, student.getClassId(), student.getSchoolId(), 1, 2);
        } else {
            //账号不存在新增
            ApiReturnObject apiReturnObject = userFeign.addAppUser3(student.getPhone(),
                    student.getClassId().toString(),
                    student.getSchoolId(),
                    student.getIdcardno(),
                    student.getStudentName(), 1);
            id = (int) apiReturnObject.getReturnObject();
        }
        student.setUserId(id);
        student.setApplicationStatus("1");
        studentService.insertTStudent(student);
        return new ApiReturnObject("200", "添加成功", "");
    }

    /**
     * 教师端
     * 添加学生
     */
    @PostMapping("/addByTea")
    public ApiReturnObject addByTea(@RequestBody TStudent student) {
        TStudent tStudent = new TStudent();
        //根据手机号判断是否存在
        if (!"".equals(student.getPhone())) {
            tStudent.setPhone(student.getPhone());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该手机号已存在", "");
            }
        }
        //根据身份证判断是否存在
        tStudent.setPhone("");
        if (!"".equals(student.getIdcardno())) {
            tStudent.setIdcardno(student.getIdcardno());
            List<TStudent> tStudents = studentService.selectTStudentList(tStudent);
            if (tStudents.size() > 0) {
                return new ApiReturnObject("201", "该身份证号已存在", "");
            }
        }
        SysAppUser appUser = new SysAppUser();
        appUser.setClassId(student.getClassId());
        appUser.setSchoolId(student.getSchoolId());
        appUser.setSysPhone(student.getPhone());
        appUser.setIdcardno(student.getIdcardno());
        appUser.setCreateTime(new Date());
        appUser.setSysRelname(student.getStudentName());

        int id;
        boolean bool = userFeign.findUserBySchoolId2(student.getPhone());
        if (bool) {
            //账号存在不新增
            //查询已存在的用户id与学生表建立关联关系
            ApiReturnObject sysUserBysysPhone = userFeign.findSysUserBysysPhone(student.getPhone());
            id = (int) sysUserBysysPhone.getReturnObject();
            //用户表对应用户添加学校id和班级id以及用户类型
            studentService.updateInfoForUser(id, student.getClassId(), student.getSchoolId(), 1, 2);
        } else {
            //账号不存在新增
            ApiReturnObject apiReturnObject = userFeign.addAppUser3(student.getPhone(),
                    student.getClassId().toString(),
                    student.getSchoolId(),
                    student.getIdcardno(),
                    student.getStudentName(), 1);
            id = (int) apiReturnObject.getReturnObject();
        }
        student.setUserId(id);
        student.setApplicationStatus("1");
        studentService.insertTStudent(student);
        return new ApiReturnObject("200", "添加成功", "");
    }

    /**
     * 教务端
     * 修改学生
     */
    @PostMapping("/update")
    public ApiReturnObject updateSave(@RequestBody TStudent student) {
        if (student.getId() != null) {
            //修改用户表
            if (student.getUserId() != null) {
                SysAppUser sysAppUser = new SysAppUser();
                sysAppUser.setId(student.getUserId().longValue());
                if (StringUtils.isNotNull(student.getClassId())) {
                    sysAppUser.setClassId(student.getClassId());
                }
                //sysAppUser.setSysRelname(student.getStudentName());
                if (StringUtils.isNotBlank(student.getIdcardno())) {
                    sysAppUser.setIdcardno(student.getIdcardno());
                }
                userFeign.updateStu(sysAppUser);
            }
            studentService.updateTStudent(student);
            return new ApiReturnObject("200", "修改成功", "");
        }
        return new ApiReturnObject("201", "缺少id", "");
    }

    /**
     * 老师端
     * 修改学生信息
     */
    @PostMapping("/updateByTea")
    public ApiReturnObject updateByTea(@RequestBody TStudent student) {
        if (student.getId() != null) {
            //设置班级id
            if (student.getUserId() != null && student.getClassId() != null) {
                SysAppUser sysAppUser = new SysAppUser();
                sysAppUser.setId(student.getUserId().longValue());
                sysAppUser.setClassId(student.getClassId());
                sysAppUser.setSysRelname(student.getStudentName());
                sysAppUser.setIdcardno(student.getIdcardno());
                userFeign.updateStu(sysAppUser);
            }
            studentService.updateTStudent(student);
            return new ApiReturnObject("200", "修改成功", "");
        }
        return new ApiReturnObject("201", "缺少id", "");
    }

    /**
     * 修改学生
     */
    @GetMapping("/updateByFeign")
    private String updateByFeign(String phone, Integer userId) {
        TStudent student = new TStudent();
        student.setPhone(phone);
        List<TStudent> tStudents = studentService.selectTStudentList(student);
        int i = 1;
        if (tStudents.size() == i) {
            TStudent build = TStudent.builder().userId(userId).id(tStudents.get(0).getId()).build();
            studentService.updateTStudent(build);
        }
        return "200";
    }

    /**
     * 修改学生
     */
    @PostMapping("/delImg")
    public ApiReturnObject delImg(@RequestBody TStudent student) {
        if (student.getId() != null) {
            TStudent tStudent = studentService.selectTStudentById(student.getId());
            //删除七牛云资源
            //QiniuUtil.deleteFileFromQiniu(tStudent.getImgUrl());
            student.setImgUrl("");
            studentService.updateTStudent(student);
            return new ApiReturnObject("200", "修改成功", "");
        }
        return new ApiReturnObject("201", "缺少id", "");
    }


    /**
     * 教师教务
     * 删除学生
     */
    @PostMapping("/del")
    public ApiReturnObject del(@RequestBody TStudent student) {
        TStudent tStudent = studentService.selectTStudentById(student.getId());
        //更改用户表的用户状态
        if (tStudent.getUserId() != null) {
            studentService.updateInfoForUser(tStudent.getUserId(), 0, 0, null, 1);
        }
        if (student.getId() != null) {
            //删除学生
            studentService.deleteTStudentById(student.getId());
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "缺少id参数", "");
    }

    /**
     * 删除学生
     */
    @PostMapping("/dels")
    private ApiReturnObject dels(@RequestBody TStudent student) {
        if (student.getIds() != null) {
            //删除学生
            studentService.deleteTStudentByIds(student.getIds());
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "缺少id参数", "");
    }

    //查询学生是否在线
    @GetMapping("/selectstate")
    public ApiReturnObject selectstate(Integer userId) {
        TStudent tStudent = studentService.selectTStudentById2(userId);
        //获取学生登录时间
        String signTime = tStudent.getSignTime();
        //获取系统当前时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        try {
            Date parse = simpleDateFormat.parse(signTime);
            Date parse1 = simpleDateFormat.parse(format);
            if (parse1.getTime() - parse.getTime() < 60000) {
                TStudent tStudent1 = new TStudent();
                tStudent1.setState(1);
                tStudent1.setUserId(userId);
                studentService.updateByUserId(tStudent1);
                return new ApiReturnObject("200", "该学生在线", "");
            } else {
                TStudent tStudent1 = new TStudent();
                tStudent1.setState(2);
                tStudent1.setUserId(userId);
                studentService.updateByUserId(tStudent1);
                return new ApiReturnObject("200", "该学生不在线", "");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new ApiReturnObject("200", "null", "");
    }

}